package cn.zt.interceptor;

import cn.zt.domain.dto.UserDTO;
import cn.zt.mapper.UserMapper;
import cn.zt.utils.UserHolder;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

/**
 * 登录校验
 */
@Configuration
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private UserMapper userMapper;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        // 获取请求路径
        String requestURI = request.getRequestURI();


        // 定义需要拦截的路径
        String[] protectedPaths = {
                "/order", "/manage", "/select/order"
        };

        // 检查请求路径是否在需要拦截的路径列表中
        for (String path : protectedPaths) {
            if (requestURI.startsWith(path)) {
                // 判断是否需要拦截，查询数据库中用户token

                // 从请求头中获取token
                String authorization = request.getHeader("authorization");
                if (authorization == null){
                    System.out.println("authorization为null");
                    response.setStatus(401);
                    return false;
                }
                String token = authorization.split(" ")[1];


                //判断token是否为空
                if (token == null || token.isEmpty()) {
                    // 没有token，需要拦截，设置状态码
                    System.out.println("拦截器拦截到请求：" + requestURI);
                    response.setStatus(401);
                    return false;
                }

                // 从数据库中查询用户token根据用户id
                String header = request.getHeader("Userid");
                if (header == null){
                    System.out.println("Userid为null");
                    response.setStatus(401);
                    return false;
                }

                Long userId = Long.valueOf(header);

                System.out.println("请求拦截器对用户" + userId + "作用token和userId都不为null");

                String yToken = userMapper.selectById(userId).getToken();

                if (!yToken.equals(token)) {
                    // token不匹配，需要拦截，设置状态码
                    System.out.println("拦截器拦截到请求：" + requestURI);
                    response.setStatus(401);
                    return false;
                }
            }
        }
        System.out.println("拦截器放行");
        // 其他页面放行
        return true;
    }

}
